import axios from 'axios';

const requestControllers = {};
const instance = axios.create({ timeout: 200000, baseURL: '/api' });

const successCodeWhiteList = [200, '00']; // 成功状态码白名单，用于接口成功状态码不一致的情况
const requestAbortWhiteList = []; // 重复请求取消白名单：例如轮询、长时间任务接口、上传图片等

instance.interceptors.request.use(
  (config) => {
    const url = config.url;
    if (requestAbortWhiteList.includes(url)) return config;

    if (requestControllers[url]) {
      requestControllers[url].abort();
      console.log('请求被中断:', url);
    }

    const controller = new AbortController();
    config.signal = controller.signal; // 挂载到 config实例的原因是，告诉axios这个请求可能被取消
    requestControllers[url] = controller;

    // 设置请求头
    config.headers['Authorization'] =
      'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbklkIjoic3lzX3VzZXI6MSIsInJuIjoiZG8zbktPUGt2UFBCcEs0VkhmdUpnUUhkV1VGTnx2bjcifQ.qUPyk0PedeLblWqSINcDT2cUb4-NqGki9lPCSmV0AP0';

    return config;
  },
  (err) => Promise.reject(err)
);

instance.interceptors.response.use(
  (res) => {
    const url = res.config.url;
    if (!requestAbortWhiteList.includes(url)) delete requestControllers[url]; // 清理不在白名单请求控制器
    if (res.status === 200 && successCodeWhiteList.includes(String(res.data.code))) return Promise.resolve(res.data);
    return Promise.reject(`请求错误：${JSON.stringify(res.data)}`);
  },
  (err) => {
    if (err.name === 'AbortError') return Promise.reject(new Error('请求被主动取消'));
    return Promise.reject(err.message);
  }
);

export default instance;